package com.zzh.h265toupin

import android.app.Activity
import android.content.Intent
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.zzh.h265toupin.databinding.ActivityPushBinding
import com.zzh.h265toupin.sockets.SocketPushServer
import com.zzh.h265toupin.utils.NetworkUtil


class TouPinPushActivity : AppCompatActivity() {
    private lateinit var binding: ActivityPushBinding

    private lateinit var mediaProjectionManager: MediaProjectionManager
    private var socketPushServer: SocketPushServer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPushBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }

    private fun initView() {
        val localIp = NetworkUtil.getWIFILocalIpAddress(this)
        binding.tvPushIp.text = localIp
        binding.btScreenPush.setOnClickListener {
            //获取录屏系统服务
            mediaProjectionManager =
                getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            //申请录屏权限，弹出录屏权限的对话框
            val intent = mediaProjectionManager.createScreenCaptureIntent()
            startActivityForResult(intent, 100)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            //获得录屏数据,Android高版本有权限问题，api27
            val mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data!!)
            val port = binding.etPushPort.text.toString().toInt()
            socketPushServer = SocketPushServer(port)
            //启动录屏推流的socket服务
            socketPushServer!!.start(mediaProjection)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        socketPushServer?.close()
        socketPushServer = null
    }
}